package com.scpii.universal.pns.action;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;

import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.json.JSONException;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.doone.comm.paginaction.Pagination;
import com.scpii.universal.action.BaseAction;
import com.scpii.universal.constant.GenericConstants;
import com.scpii.universal.pns.dto.BodyDto;
import com.scpii.universal.pns.dto.ClientUserDto;
import com.scpii.universal.pns.dto.PnsMessageV2Dto;
import com.scpii.universal.pns.entity.Devices;
import com.scpii.universal.pns.entity.PnsMessages;
import com.scpii.universal.pns.service.ClientUserManageService;
import com.scpii.universal.pns.service.DevicesService;
import com.scpii.universal.pns.service.PnsMessageV2Service;
import com.scpii.universal.util.EhCacheManager;
import com.scpii.universal.util.FileUploadUtil;
import com.scpii.universal.util.ImgAndFilePath;
import com.scpii.universal.util.StreamUtil;

@Controller
@Scope("prototype")
public class PnsMessageV2Action extends BaseAction {

	@Resource
	private PnsMessageV2Service pnsMessageV2Service;

	@Resource
	private ClientUserManageService clientUserManageService;

	@Resource
	private DevicesService devicesService;

	/**
	 * serialVersionUID
	 */
	private static final long serialVersionUID = 7044302833381431997L;

	private Pagination page = new Pagination();

	private List<PnsMessages> msgList;

	private Long messageId;

	private PnsMessageV2Dto msgDto;

	private String[] deviceModels;

	private ClientUserDto condition;

	private List<String> sysVersions;

	private Devices devices;

	private Boolean showUserList = false;

	private List<Map<String, Object>> users;

	private List<BodyDto> bodyDtos;

	private PnsMessages pnsMessages;

	private File fileMaterial;

	private String fileMaterialFileName;

	private List<Long> ckUserBox;

	private Boolean allPicker;

	private Long id;

	private Integer totalCount;

	private Integer pageNum;

	private Integer pageSize;

	public String getPushManageInit() {
		if (getSelectPerPage("page") == -1) {
			page.setPageRecord(GenericConstants.PAGE_NO);
		} else {
			page.setPageRecord(getSelectPerPage("page"));
		}
		if (getQueryFlag("page") == -1) {
			page.setTotalRecord(pnsMessageV2Service
					.getPushManageInitCount(getUserInfo().getAppId()));
		} else {
			page.setTotalRecord(getQueryFlag("page"));
		}
		setPageParameters(page, "page");
		msgList = pnsMessageV2Service.getPushManageInit(getUserInfo()
				.getAppId(), page.getCurrentPage(), page.getPageRecord());
		return SUCCESS;
	}

	public String delPushMessage() {
		pnsMessageV2Service.removeMessage(messageId);
		return SUCCESS;
	}

	public String addPushMessage() {
		totalCount = clientUserManageService.getClientUserInitCount(
				getUserInfo().getAppId(), condition);
		String[] models = devicesService.getDevicesModelsByAppId(getUserInfo()
				.getAppId());
		deviceModels = models;
		return SUCCESS;
	}

	public void upload() throws IOException {
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setContentType("text/plain");
		response.setCharacterEncoding("utf-8");
		if (fileMaterial != null) {
			String absolutePath = getWebAppsRealPath() + getImgBasePath()
					+ ImgAndFilePath.PNS;
			File file = new File(absolutePath);
			if (!file.exists()) {
				file.mkdirs();
			}
			String filePath = absolutePath + File.separator
					+ FileUploadUtil.generateIconName() + ".png";
			String serverPath = StreamUtil
					.uploadActiveImgs(fileMaterial, filePath)
					.replace(getWebAppsRealPath(), "").replaceAll("\\\\", "/");
			response.getWriter().print(serverPath);
		} else {
			response.getWriter().print("error");
		}
	}

	public String addMessage() {
		Map<String, String> userTypes = new HashMap<String, String>();
		userTypes.put("NORMAL", "会员");
		userTypes.put("NOT_VERIF", "未验证");
		userTypes.put("ANON", "匿名");

		String serverUrl = EhCacheManager.getObject(
				GenericConstants.SERVER_URL_PREFIX).toString();
		if (bodyDtos != null && bodyDtos.size() != 0) {
			String jsonBodyDtos = JSONArray.fromObject(bodyDtos).toString();
			if (!StringUtils.isBlank(jsonBodyDtos)) {
				jsonBodyDtos = jsonBodyDtos.replaceAll(serverUrl, "");
			}
			pnsMessages.setBody(jsonBodyDtos);
		}
		if (!StringUtils.isBlank(pnsMessages.getIcon())) {
			pnsMessages.setIcon(pnsMessages.getIcon().replace(serverUrl, ""));
		}
		if (condition != null) {
			String searchCondition = "";
			if (!StringUtils.isBlank(condition.getDeviceType())) {
				searchCondition += condition.getDeviceType() + "|";
			}
			if (!StringUtils.isBlank(condition.getUserType())) {
				searchCondition += userTypes.get(condition.getUserType()) + "|";
			}
			if (!ArrayUtils.isEmpty(condition.getDeviceModel())) {
				searchCondition += StringUtils.join(condition.getDeviceModel(),
						",") + "|";
			}
			if (!"昵称/用户名".equals(condition.getUserName())
					&& !StringUtils.isBlank(condition.getUserName())) {
				searchCondition += condition.getUserName() + "|";
			}
			searchCondition = StringUtils.substringBeforeLast(searchCondition,
					"|");
			if (StringUtils.isBlank(searchCondition) && null != allPicker
					&& true == allPicker) {
				searchCondition = "全部";
			}
			pnsMessages.setSearchCondition(searchCondition);
		}
		if (ckUserBox != null && (allPicker == null || allPicker == false)
				&& ckUserBox.size() != 0) {
			String[] ckUserArry = new String[ckUserBox.size()];
			for (int i = 0; i < ckUserBox.size(); i++) {
				ckUserArry[i] = String.valueOf(ckUserBox.get(i));
			}
			String[] userNames = clientUserManageService
					.getUserNamesByIds(ckUserArry);
			pnsMessages.setSearchCondition(StringUtils.join(userNames, "|"));
		}
		pnsMessages.setMessageStatus(1);

		pnsMessageV2Service.save(pnsMessages, allPicker, ckUserBox,
				getUserInfo().getAppId(), condition);
		request.setAttribute("msg", "添加成功");

		return SUCCESS;
	}

	public String editMessage() throws JSONException {
		showUserList = false;
		Date now = new Date();
		String serverUrl = EhCacheManager.getObject(
				GenericConstants.SERVER_URL_PREFIX).toString();
		request.setAttribute("serverUrl", serverUrl);
		pnsMessages = pnsMessageV2Service.get(id);
		if (pnsMessages.getStartTime().before(now)) {
			pnsMessages.setFlag(0);
		}
		if (pnsMessages.getStartTime().after(now)) {
			pnsMessages.setFlag(1);
		}
		return SUCCESS;
	}

	public String doEditMessage() {
		String serverUrl = EhCacheManager.getObject(
				GenericConstants.SERVER_URL_PREFIX).toString();
		PnsMessages persistMessages = pnsMessageV2Service.get(pnsMessages
				.getId());
		if (bodyDtos != null && bodyDtos.size() != 0) {
			String jsonBodyDtos = JSONArray.fromObject(bodyDtos).toString();
			if (!StringUtils.isBlank(jsonBodyDtos)) {
				jsonBodyDtos = jsonBodyDtos.replaceAll(serverUrl, "");
			}
			pnsMessages.setBody(jsonBodyDtos);
		}
		if (!StringUtils.isBlank(pnsMessages.getIcon())) {
			pnsMessages.setIcon(pnsMessages.getIcon().replace(serverUrl, ""));
		}
		persistMessages.setStartTime(pnsMessages.getStartTime());
		persistMessages.setExpireTime(pnsMessages.getExpireTime());
		persistMessages.setTitle(pnsMessages.getTitle());
		persistMessages.setSummary(pnsMessages.getSummary());
		persistMessages.setIcon(pnsMessages.getIcon());
		persistMessages.setBody(pnsMessages.getBody());
		pnsMessageV2Service.updateMessages(persistMessages);
		return SUCCESS;
	}

	public String pnsList() {
		totalCount = clientUserManageService.getClientUserInitCount(
				getUserInfo().getAppId(), condition);
		users = clientUserManageService.getClientUserInit(getUserInfo()
				.getAppId(), condition, pageNum, pageSize);
		showUserList = true;
		return SUCCESS;
	}

	public String pnsSelectedList() {

		users = clientUserManageService.getClientUserInit(getUserInfo()
				.getAppId(), condition, pageNum, pageSize);
		showUserList = true;
		return SUCCESS;
	}

	public void pnsSelectedListCount() throws IOException {
		totalCount = clientUserManageService.getClientUserInitCount(
				getUserInfo().getAppId(), condition);
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setContentType("text/plain");
		response.setCharacterEncoding("utf-8");
		response.getWriter().print(totalCount);
	}

	public Pagination getPage() {
		return page;
	}

	public void setPage(Pagination page) {
		this.page = page;
	}

	public List<PnsMessages> getMsgList() {
		return msgList;
	}

	public void setMsgList(List<PnsMessages> msgList) {
		this.msgList = msgList;
	}

	public PnsMessageV2Dto getMsgDto() {
		return msgDto;
	}

	public void setMsgDto(PnsMessageV2Dto msgDto) {
		this.msgDto = msgDto;
	}

	public Long getMessageId() {
		return messageId;
	}

	public void setMessageId(Long messageId) {
		this.messageId = messageId;
	}

	public String[] getDeviceModels() {
		return deviceModels;
	}

	public void setDeviceModels(String[] deviceModels) {
		this.deviceModels = deviceModels;
	}

	public List<String> getSysVersions() {
		return sysVersions;
	}

	public void setSysVersions(List<String> sysVersions) {
		this.sysVersions = sysVersions;
	}

	public Devices getDevices() {
		return devices;
	}

	public void setDevices(Devices devices) {
		this.devices = devices;
	}

	public Boolean getShowUserList() {
		return showUserList;
	}

	public void setShowUserList(Boolean showUserList) {
		this.showUserList = showUserList;
	}

	public List<Map<String, Object>> getUsers() {
		return users;
	}

	public void setUsers(List<Map<String, Object>> users) {
		this.users = users;
	}

	public PnsMessages getPnsMessages() {
		return pnsMessages;
	}

	public void setPnsMessages(PnsMessages pnsMessages) {
		this.pnsMessages = pnsMessages;
	}

	public File getFileMaterial() {
		return fileMaterial;
	}

	public void setFileMaterial(File fileMaterial) {
		this.fileMaterial = fileMaterial;
	}

	public String getFileMaterialFileName() {
		return fileMaterialFileName;
	}

	public void setFileMaterialFileName(String fileMaterialFileName) {
		this.fileMaterialFileName = fileMaterialFileName;
	}

	public List<Long> getCkUserBox() {
		return ckUserBox;
	}

	public void setCkUserBox(List<Long> ckUserBox) {
		this.ckUserBox = ckUserBox;
	}

	public Boolean getAllPicker() {
		return allPicker;
	}

	public void setAllPicker(Boolean allPicker) {
		this.allPicker = allPicker;
	}

	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public ClientUserDto getCondition() {
		return condition;
	}

	public void setCondition(ClientUserDto condition) {
		this.condition = condition;
	}

	public List<BodyDto> getBodyDtos() {
		return bodyDtos;
	}

	public void setBodyDtos(List<BodyDto> bodyDtos) {
		this.bodyDtos = bodyDtos;
	}

	public Integer getTotalCount() {
		return totalCount;
	}

	public void setTotalCount(Integer totalCount) {
		this.totalCount = totalCount;
	}

	public Integer getPageNum() {
		return pageNum;
	}

	public void setPageNum(Integer pageNum) {
		this.pageNum = pageNum;
	}

	public Integer getPageSize() {
		return pageSize;
	}

	public void setPageSize(Integer pageSize) {
		this.pageSize = pageSize;
	}

}
